from fastapi import APIRouter
from fastapi import Request
from service.RecordService import RecordService
from util.MyExceptionHandler import MyExceptionHandler
import inspect
import json
from util import Logger
from StatusCode import StatusCode

router = APIRouter(tags=["档案管理路由"])


@router.get("/record/list")
async def listRecord(request: Request):
    try:
        json_data = dict(request.query_params)
        data = RecordService().getRecords(json_data)
        response = {
            "msg": StatusCode.RESPONSE_SUCCESS,
            "code": 200,
            "data": data.to_dict(orient="records"),
            "total": data.shape[0],
        }
    except Exception as e:
        Logger.logger(e)
        response = MyExceptionHandler().postException(
            inspect.currentframe().f_code.co_name, e
        )
    return response


@router.get("/record/info")
def getRecordInfo(request: Request):
    try:
        json_data = dict(request.query_params)
        data = RecordService().getRecordInfo(json_data)
        if len(data) == 0:
            response = {
                "code": StatusCode.RESPONSE_FAIL,
                "msg": "获取档案信息失败,请检查数据后重试",
            }
            return response
        response = {
            "code": StatusCode.RESPONSE_SUCCESS,
            "data": data,
        }
    except Exception as e:
        Logger.logger(e)
        response = MyExceptionHandler().postException(
            inspect.currentframe().f_code.co_name, e
        )
    return response


@router.post("/record/update")
async def updateRecord(request: Request):
    try:
        json_data = await request.json()
        flag = RecordService().updateRecord(json_data)
        response = {"code": flag}
        if flag != StatusCode.RESPONSE_SUCCESS:
            response["msg"] = "修改档案信息失败,请检查数据后重试"
    except Exception as e:
        Logger.logger(e)
        response = MyExceptionHandler().postException(
            inspect.currentframe().f_code.co_name, e
        )
    return response


@router.post("/record/add")
async def addRecord(request: Request):
    try:
        json_data = await request.json()
        flag = RecordService().addRecord(json_data)
        response = {"code": flag}
        if flag != StatusCode.RESPONSE_SUCCESS:
            response["msg"] = "添加档案信息失败,请检查数据后重试"
    except Exception as e:
        Logger.logger(e)
        response = MyExceptionHandler().postException(
            inspect.currentframe().f_code.co_name, e
        )
    return response


@router.get("/record/del")
def delRecord(request: Request):
    try:
        json_data = dict(request.query_params)
        flag = RecordService().delRecord(json_data)
        response = {"code": flag}
        if flag != StatusCode.RESPONSE_SUCCESS:
            response["msg"] = "删除档案信息失败,请检查数据后重试"
    except Exception as e:
        Logger.logger(e)
        response = MyExceptionHandler().postException(
            inspect.currentframe().f_code.co_name, e
        )
    return response
